<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { series, tooltip, windowResize, xAxis, yAxis } from '@/views/common'
import moment from 'moment'
import { cgBlockRequest, cgLevelRequest, cgResultRequest } from '@/views/cockpit/projectSection/api'
import { isSuccess } from '@/views/cockpit/common'
import { getDictionary } from '@/views/science/api/technologyawards'
import { fontSizeRem } from '@/utils/utils'

const yearValue = ref<string>(moment().format('YYYY'))
const levelValue = ref<string>('')
const typeValue = ref<string>('')
const levelOptions = ref<Record<string, string>[]>([])
const typeOptions = ref<Record<string, string>[]>([])
const initOptions = () => {
  getDictionary(['KHGL_KJSL_HJJB']).then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || {}
      // 奖项级别
      levelOptions.value = data.KHGL_KJSL_HJJB || []
    }
  })
}
const projectEl = ref<HTMLDivElement>()
const levelEl = ref<HTMLDivElement>()
const blockEl = ref<HTMLDivElement>()
let projectChart: ECharts
let levelChart: ECharts
let blockChart: ECharts
const countryColors = ['#933C6F', '#6258E8', '#9A58E8', '#8DA01A', '#208D51','#4396A5','#5424B0','#9B8B48','#5B841E','#035963']
// 获取对应渲染图表数据 - 左侧图表数据
const initProjectChart = async () => {
  let lineX = []
  let lineY = []
  const res = await cgResultRequest(yearValue.value)
  if (isSuccess(res)) {
    const data = res.data.data || []
    lineX = data.map((t) => t.type) || []
    lineY = data.map((t) => t.num) || []
  }
  if (projectChart) projectChart.dispose()
  projectChart = echarts.init(projectEl.value)
  projectChart.setOption({
    tooltip,
    grid: {
      top: '100',
      left: '10',
      right: '0',
      bottom: '10',
      containLabel: true,
    },
    xAxis: {
      axisPointer: {
        type: 'shadow',
      },
      ...xAxis(lineX, false),
      // axisLine: {
      //   show: false,
      // },
    },
    yAxis: {
      ...yAxis(true),
      // axisLine: {
      //   show: true,
      //   lineStyle: { color: '#bfc0c5' },
      // },
      splitLine: {
        lineStyle: {
          color: 'rgba(131,101,101,0.2)',
          type: 'dashed',
        },
      },
      minInterval: 1,
    },
    series: {
      ...series(lineY, '', '项目成果', '个'),
      label: {
        show: true,
        position:'top',
        color: '#fff',
      },
      // itemStyle: {
      //   color: () => {
      //     return countryColors[Math.floor(Math.random() * 10)]
      //   },
      // },
      barWidth: fontSizeRem(0.3),
      itemStyle: {
        // color: '#C7A746',
        color: function (params) {
          //展示正值的柱子，负数设为透明
          let colorArr =
            params.value > 0
              ? [countryColors[Math.floor(Math.random() * 10)], '#08103B']
              : ['#08103B', countryColors[Math.floor(Math.random() * 10)]]
          return new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: colorArr[0], // 0% 处的颜色
              },
              {
                offset: 1,
                color: colorArr[1], // 100% 处的颜色
              },
            ],
            false
          )
        },
        barBorderRadius: [30, 30, 0, 0],
      },
    },
  })
}
// 获取对应渲染图表数据 - 右侧图表数据
const initChangeOption = () => {
  const options = (levelOptions.value.find((t) => t.itemValue === levelValue.value)?.children ||
    []) as Record<string, string>[]
  typeValue.value = ''
  typeOptions.value = options
  initChart()
}
const initChart = async () => {
  let lineX = []
  let lineY = []
  const res = await cgLevelRequest(levelValue.value, typeValue.value)
  if (isSuccess(res)) {
    let data = res.data.data || []
    data = data.filter((t) => t.year) 
    lineX = data.map((t) => t.year) || []
    lineY = data.map((t) => t.num) || []
  }
  if (levelChart) levelChart.dispose()
  levelChart = echarts.init(levelEl.value)
  levelChart.setOption({
    tooltip,
    grid: {
      top: '20',
      left: '0',
      right: '2',
      bottom: '10',
      containLabel: true,
    },
    xAxis: {
      axisPointer: {
        type: 'shadow',
      },
      ...xAxis(lineX, false, lineX.length),
    },
    yAxis: {
      name: '单位 个',
      ...yAxis(true),
      splitLine: {
        lineStyle: {
          color: 'rgba(131,101,101,0.2)',
          type: 'dashed',
        },
      },
    },
    series: {
      ...series(lineY, '', '奖项级别', '个'),
      label: {
        show: true,
        position: 'top',
        color: '#fff',
      },
      // itemStyle: {
      //   color: () => {
      //     return countryColors[Math.floor(Math.random() * 10)]
      //   },
      // },
      barWidth: fontSizeRem(0.3),
      itemStyle: {
        // color: '#C7A746',
        color: function (params) {
          //展示正值的柱子，负数设为透明
          let colorArr =
            params.value > 0
              ? [countryColors[Math.floor(Math.random() * 10)], '#08103B']
              : ['#08103B', countryColors[Math.floor(Math.random() * 10)]]
          return new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: colorArr[0], // 0% 处的颜色
              },
              {
                offset: 1,
                color: colorArr[1], // 100% 处的颜色
              },
            ],
            false
          )
        },
        barBorderRadius: [30, 30, 0, 0],
      },
    },
  })
  cgBlockRequest().then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || []
      const lineX1 = data.map((t) => t.classId) || []
      const lineY1 = data.map((t) => t.num) || []
      if (blockChart) blockChart.dispose()
      blockChart = echarts.init(blockEl.value)
      blockChart.setOption({
        tooltip,
        grid: {
          top: '20',
          left: '0',
          right: '2',
          bottom: '10',
          containLabel: true,
        },
        xAxis: {
          axisPointer: {
            type: 'shadow',
          },
          ...xAxis(lineX1, false, lineX1.length),
        },
        yAxis: {
          ...yAxis(true),
          splitLine: {
            lineStyle: {
              color: 'rgba(131,101,101,0.2)',
              type: 'dashed',
            },
          },
        },
        series: {
          ...series(lineY1, '', '业务板块', '个'),
          label: {
            show: true,
            position: 'top',
            color: '#fff',
          },
          // itemStyle: {
          //   color: () => {
          //     return countryColors[Math.floor(Math.random() * 10)]
          //   },
          // },
          barWidth: fontSizeRem(0.3),
          itemStyle: {
            // color: '#C7A746',
            color: function (params) {
              //展示正值的柱子，负数设为透明
              let colorArr = params.value > 0 ? [countryColors[Math.floor(Math.random() * 10)], '#08103B'] : ['#08103B', countryColors[Math.floor(Math.random() * 10)]]
              return new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: colorArr[0], // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: colorArr[1], // 100% 处的颜色
                  },
                ],
                false
              )
            },
            barBorderRadius: [30, 30, 0, 0],
          },
        },
      })
    } else if (blockChart) blockChart.dispose()
  })
}
const windowEvent = () => {
  windowResize(300, () => {
    if (projectChart) projectChart.resize()
    if (levelChart && blockChart) {
      levelChart.resize()
      blockChart.resize()
    }
  })
}
onMounted(() => {
  initOptions()
  initProjectChart()
  initChart()
  window.addEventListener('resize', () => {
    windowEvent()
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', windowEvent)
})
</script>

<template>
  <div class="chartContent">
    <div class="result mr20">
      <div class="search mb10">
        <el-date-picker
          v-model="yearValue"
          type="year"
          placeholder="选择年度"
          value-format="YYYY"
          format="YYYY"
          clearable
          @change="initProjectChart"
        />
      </div>
      <div class="modal">
        <span class="modalTitle l10">项目成果</span>
        <div ref="projectEl" class="chat"></div>
      </div>
    </div>
    <div class="statics modal">
      <span class="modalTitle l10" >获奖统计</span>
      <div class="search mb10" style="margin-bottom: 35px">
        <el-select
          v-model="levelValue"
          clearable
          class="m-2 mr20"
          placeholder="奖项级别"
          @change="initChangeOption"
        >
          <el-option
            v-for="item in levelOptions"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
        <el-select
          v-model="typeValue"
          clearable
          class="m-2 mr20"
          placeholder="奖项类别"
          @change="initChart"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </div>
      <div class="staticsContent">
        <div class="rect mb10">
          <span class="desc">奖项级别</span>
          <div ref="levelEl" class="chat"></div>
        </div>
        <div class="rect">
          <span class="desc">业务板块</span>
          <div ref="blockEl" class="chat"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/css/theme';
@import '../../common';
.chartContent {
  .statics,
  .result {
    display: flex;
    flex-direction: column;
    flex: 1 1 0;
    max-width: 50%;
  }
  .modal {
    position: relative;
    display: flex;
    flex: 1 1 0;
    padding: 10px;
    background-image: url(../../img/project-bg.png);
    background-size: 100% 100%;
    // border: 1px solid $primary-color;
  }
  .statics {
    .search {
      margin-top: 2vh;
      display: flex;
      justify-content: end;
    }
  }
  .staticsContent {
    display: flex;
    flex-direction: column;
    flex: 1 1 0;
    .rect {
      position: relative;
      display: flex;
      flex: 1 1 0;
      padding-left: 30px;
      padding-top: 10px;
      margin-top: 20px;
      max-height: 50%;
      .desc {
        // width: 20px;
        position: absolute;
        left: 3vh;
        top: -1.5vh;
        transform: translateY(-50%);
        color: #fff;
        // font-weight: bold;
        font-size: 1.6vh;
      }
    }
  }
}
</style>
